package com.dgut.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgut.Utils.AppUtil;
import com.dgut.springsecurity.Details.UserAccountDetail;
import com.dgut.springsecurity.handler.UserLoginFailureHandler;
import com.dgut.usermanager.entity.*;
import com.dgut.usermanager.service.HouseService;
import com.dgut.usermanager.service.ImageService;
import com.dgut.usermanager.service.UserAccountService;
import com.dgut.usermanager.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
public class UserController {

    @Autowired
    UserAccountService userAccountService;
    @Autowired
    UserService userService;
    @Autowired
    HouseService houseService;
    @Autowired
    ImageService imageService;

    @Autowired
    UserLoginFailureHandler userLoginFailureHandler;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    // 前台-注册界面
    /*@GetMapping("/user/registry_frontend")
    String userRegistry() {
        return "user/register_frontend";
    }*/
    // 前台-登录界面
    /*@GetMapping("/user/login_frontend")
    String userLogin() {
        return "user/login_frontend";
    }*/







    @RequestMapping(value="/user/login_frontend",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    String userWxLogin(/*HttpServletRequest request*/) throws IOException {
        //String errMsg=request.getParameter("errMsg");
        //System.out.println(username);
        //response.sendRedirect("/user");
        //System.out.println(request.getParameter("username"));
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        System.out.println("addv");
        //System.out.println(errMsg);
        //System.out.println(request);
        //request.setAttribute("errMsg",request.getAttribute("errMsg"));

        return "login_frontend";
    }

    @GetMapping("/user/attribute")//@ResponseBody
    @ResponseBody
    String userWxLoginAt(HttpServletRequest request) {
        //String errMsg=new String(request.getParameter("errMsg").getBytes("iso-8859-1"),"gbk");
        //errMsg= URLEncoder.encode(errMsg,"");
        String errMsg=request.getParameter("errMsg");
        System.out.println(errMsg);
        System.out.println(request);
        request.setAttribute("errMsg",errMsg);

        return errMsg;
    }

    @RequestMapping(value="/user/login",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    String userLoginWxIndex(HttpServletRequest request) {
        UserAccount userAccount= userAccountService.findUserAccountByAccount(request.getParameter("username"));
        userLoginFailureHandler.setNumber(3);
        /*if(user==null){
            model.addAttribute("error","用户名不存在！！！");
            return "login_frontend";
        }else if(user.getPassword()!=password) {
            model.addAttribute("error","密码错误！！！");
            return "login_frontend";
        }*/
        System.out.println(userAccount);
        System.out.println(request.getParameter("username"));
        //model.addAttribute("userAccount", userAccount);
        return "user";

    }
    @GetMapping("/user")
    @ResponseBody
    MainInformation userWxIndex(/*HttpServletRequest request*/) {
        UserAccountDetail userAccountDetail=(UserAccountDetail)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserAccount userAccount=userAccountService.findUserAccountByAccount(userAccountDetail.getUsername());
        MainInformation mainInformation=new MainInformation();
        mainInformation.setUserAccount(userAccount.getAccount());
        if(userAccount.getUser()!=null){
            /*MainInformation mainInformation=new MainInformation();*/
            User user=userAccount.getUser();
            House house=houseService.findHouseByUserId(user.getId());
            Image image=imageService.findImageByUserId(user.getId());
            mainInformation.setBuilding(house.getBuilding());
            mainInformation.setHeadimage(image.getHeadimage());
            mainInformation.setRoomNumber(house.getRoomNumber());
            mainInformation.setTel(user.getTel());
            mainInformation.setUserIdCard(user.getUserIdCard());
            mainInformation.setUsername(user.getUsername());
            mainInformation.setNumber(user.getNumber());
            mainInformation.setLastestTime(user.getLastestTime());
            mainInformation.setLastestTemp(user.getLastestTemp());
            System.out.println(userAccountDetail);
            return mainInformation;
        }
        else{
            return mainInformation;
        }

    }

    //注册
    @PostMapping("/user/add")
    @ResponseBody
    String userAdd(@RequestParam("openid")String openid,@RequestParam("username")String username, @RequestParam("password1")String password1,@RequestParam("password2")String password2) {
        if(password1.equals(password2)&&userAccountService.findUserAccountByAccount(username)==null) {
            UserAccount userAccount = new UserAccount();
            userAccount.setAccount(username);
            userAccount.setPassword(bCryptPasswordEncoder.encode(password1.trim()));
            userAccount.setOpenId(openid);
            userAccount.setPower("USER");
            userAccountService.AddUserAccount(userAccount);
            return "注册成功！！！";
        }else if(userAccountService.findUserAccountByAccount(username)!=null)
            return "用户名已存在注册失败！！！";
        else
            return "确认密码不相同！！！";
    }
    //住户修改自己的信息
    @GetMapping("/user/update")
    String userUpdate(UserAccount userAccount, Model model) {

        userAccountService.updateUserAccount(userAccount);
        return "user/user";
    }
    @GetMapping("/user/QRcode")
    @ResponseBody
    String userQRcode(@RequestParam("imagePath")String imagePath) {
        System.out.println("刘小姐");

        System.out.println(imagePath);
        return "成功";
    }




    /**

     * <pre>

     * Description: wechat OAuth2.0

     * Author:        lllx

     * Version:        1.0

     * Created at:    2018/2/1

     * </pre>

     */

    @PostMapping("/user/wx/getOpenId")
    @ResponseBody
    public String openId(@RequestParam("js_code") String code){

        String url = AppUtil.wxLoginUrl+"?appid="+ AppUtil.appId +"&secret="+ AppUtil.secret+"&js_code="+code+"&grant_type=authorization_code";
        /*RequestEntity<Void> requestEntity=RequestEntity.post(URI.create(url))
                .headers(httpHeaders->httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();*/
        RestTemplate restTemplate = new RestTemplate();
        /*ResponseEntity<String> responseEntity=restTemplate.exchange(requestEntity,String.class);
        String body =responseEntity.getBody();*/
        String jsonString = restTemplate.getForObject(url, String.class);
        JSONObject json= JSON.parseObject(jsonString);;
        Map<String, Object> jsonMap = JSONObject.toJavaObject(json, Map.class);
        String openid = (String) jsonMap.get("openid");
        System.out.println(jsonMap);
        System.out.println(code);
        System.out.println(url);
        System.out.println(openid);
        System.out.println(json);

        return openid;
    }


        @RequestMapping("/upload")

        public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

            String account=request.getParameter("account");
            String username=request.getParameter("username");
            String userIdCard=request.getParameter("userIdCard");
            String tel=request.getParameter("tel");
            Integer building=Integer.valueOf(request.getParameter("building"));request.getParameter("building");
            Integer roomNumber=Integer.valueOf(request.getParameter("roomNumber"));

            UserAccount userAccount=userAccountService.findUserAccountByAccount(account);
            System.out.println(userAccount);
            if(userAccount.getUser()==null) {

                User user = new User();
                user.setUsername(username);
                user.setUserIdCard(userIdCard);
                user.setTel(tel);
                /*user.setUserAccount(userAccount);
                user.setHouse(house);
                user.setImage(image);*/
                System.out.println("csdv");
                user = userService.AddUser(user);
                System.out.println("csdvx");


                House house = new House();
                house.setBuilding(building);
                house.setRoomNumber(roomNumber);
                house.setUser(user);
                house = houseService.AddHouse(house);

                MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
                MultipartFile multipartFile = req.getFile("file");
                System.out.println(multipartFile);
                byte[] imgBytes = multipartFile.getBytes();


                Image image = new Image();
                image.setHeadimage(imgBytes);
                image.setUser(user);
                image = imageService.AddImage(image);

                userAccount.setUser(user);
                userAccountService.updateUserAccount(userAccount);
            }
            else{
                User user = userAccount.getUser();
                user.setUsername(username);
                user.setUserIdCard(userIdCard);
                user.setTel(tel);
                System.out.println("csdv");
                user = userService.updateUser(user);
                System.out.println("csdvx");
                House house = houseService.findHouseByUserId(user.getId());
                house.setBuilding(building);
                house.setRoomNumber(roomNumber);
                house.setUser(user);
                house = houseService.updateHouse(house);

                MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
                MultipartFile multipartFile = req.getFile("file");
                byte[] imgBytes = multipartFile.getBytes();


                Image image = imageService.findImageByUserId(user.getId());
                image.setHeadimage(imgBytes);
                image.setUser(user);
                image = imageService.updateImage(image);

            }

        }

    @GetMapping("/userAccount")
    @ResponseBody
    MainInformation userAccountWxIndex(HttpServletRequest request) {
        MainInformation mainInformation=new MainInformation();
        String account=request.getParameter("account");
        UserAccount userAccount=userAccountService.findUserAccountByAccount(account);
        User user=userAccount.getUser();
        House house=houseService.findHouseByUserId(user.getId());
        Image image=imageService.findImageByUserId(user.getId());
        mainInformation.setBuilding(house.getBuilding());
        mainInformation.setHeadimage(image.getHeadimage());
        mainInformation.setRoomNumber(house.getRoomNumber());
        mainInformation.setTel(user.getTel());
        mainInformation.setUserIdCard(user.getUserIdCard());
        mainInformation.setUsername(user.getUsername());
        mainInformation.setNumber(user.getNumber());
        mainInformation.setLastestTime(user.getLastestTime());
        mainInformation.setLastestTemp(user.getLastestTemp());
        System.out.println(user);
        return mainInformation;

    }


}






